package org.rapan.EJB;

import java.util.Set;
import java.util.TreeSet;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.rapan.exceptions.EmailTakenException;
import org.rapan.jpa.Company;

@Stateless
public class CompanyBean implements CompanyInt{
	
	@PersistenceContext(unitName = "Consult")
	private EntityManager em;

	@Override
	public void createCompany(String name, String email)
			throws EmailTakenException {
		TypedQuery<Long> q = em.createQuery(
				"Select count(c) from Company c where c.email = :email",
				Long.class);
		q.setParameter("email", email);
		if (q.getSingleResult() > 0)
			throw new EmailTakenException();
		Company c = new Company();
		c.setName(name);
		c.setEmail(email);
		em.persist(c);
		em.flush();
	}

	@Override
	public Company viewCompany(long id) {
		try {
		Company c = em.find(Company.class, id);
		return c;
		} catch (IllegalArgumentException e) {
		return null;
		}
	}

	@Override
	public Set<Company> getAllCompanies() {
		TypedQuery<Company> q = em.createQuery("From Company",
				Company.class);
		Set<Company> comSet = new TreeSet<Company>();
		comSet.addAll(q.getResultList());
		return comSet;
	}

}
